<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="工程项目" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入工程项目名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购项目" prop="procurementProjectName">
        <el-input
          v-model="queryParams.procurementProjectName"
          placeholder="请输入采购项目名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目类别" prop="procurementCategory">
        <el-input
          v-model="queryParams.procurementCategory"
          placeholder="请输入项目类别"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采购方式" prop="procurementMethod">
        <el-input
          v-model="queryParams.procurementMethod"
          placeholder="请输入采购方式"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 240px">
          <el-option label="未处理" :value="-1" />
          <el-option label="作废" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="预留" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['projectManager:project:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['projectManager:project:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['projectManager:project:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['projectManager:project:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['projectManager:project:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-s-operation"
          size="mini"
          @click="handleColumnSelect"
        >字段选择</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 动态列 -->
      <el-table-column
        v-for="column in visibleColumns"
        :key="column.prop"
        :label="column.label"
        align="center"
        :prop="column.prop"
      />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['projectManager:project:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleReview(scope.row)"
            v-hasPermi="['projectManager:project:review']"
          >审核意见</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projectManager:project:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <Create
      v-if="openCreate"
      :visible.sync="openCreate"
      :data="formData"
      :is-edit="isEdit"
      @submit="onSubmit"
    />

    <!-- 审核意见弹窗 -->
    <el-dialog
      title="审核意见"
      :visible.sync="openReview"
      width="800px"
      append-to-body
      @close="closeReview"
    >
      <el-form ref="reviewForm" :model="reviewForm" :rules="reviewRules" label-width="120px">
        <el-form-item label="工程项目" prop="projectName">
          <el-input v-model="reviewForm.projectName" readonly />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio label="-1">未处理</el-radio>
            <el-radio label="0">作废</el-radio>
            <el-radio label="1">审核通过</el-radio>
            <el-radio label="2">预留</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="comment">
          <el-input
            v-model="reviewForm.comment"
            type="textarea"
            :rows="4"
            resize="vertical"
            placeholder="请输入审核意见"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReview" :loading="reviewLoading">确 定</el-button>
        <el-button @click="closeReview">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 字段选择弹窗 -->
    <el-dialog
      title="字段选择"
      :visible.sync="openColumnSelect"
      width="600px"
      append-to-body
      @close="closeColumnSelect"
    >
      <el-form>
        <el-form-item label="选择显示字段">
          <el-checkbox-group v-model="selectedColumns">
            <el-checkbox v-for="column in allColumns" :key="column.prop" :label="column.prop">{{ column.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveColumnSelection">确 定</el-button>
        <el-button @click="closeColumnSelect">取 消</el-button>
        <el-button type="text" @click="selectAllColumns">全选</el-button>
        <el-button type="text" @click="clearColumnSelection">清空</el-button>
      </div>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog
      title="数据导入"
      :visible.sync="openImport"
      width="500px"
      append-to-body
      @close="closeImport"
    >
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="80px">
        <el-form-item label="模板下载">
          <el-button size="small" type="text" @click="handleDownloadTemplate">
            <i class="el-icon-download"></i> 下载导入模板
          </el-button>
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            下载标准导入模板，按照模板格式填写数据
          </div>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url + '?updateSupport=' + (upload.updateSupport ? 1 : 0)"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="false"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">
              <el-checkbox v-model="upload.updateSupport">是否更新已经存在的项目数据</el-checkbox>
              <br />
              仅允许导入xls、xlsx格式文件。
              <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="handleDownloadTemplate">下载模板</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="closeImport">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProject, getProject, delProject, addProject, updateProject, exportProject, reviewProject, importProject } from "@/api/projectManager/project";
import Editor from '@/components/Editor';
import Create from './creat.vue'; // 引入新组件

export default {
  name: "Project",
  components: { Editor, Create},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工程项目信息表格数据
      projectList: [],
      // 弹出层标题
      title: "",
      // 控制 Create 弹窗显示
      openCreate: false,
      // 传递给 Create 的表单数据
      formData: {},
      // 判断是新增还是编辑
      isEdit: false,
      // 控制审核弹窗显示
      openReview: false,
      // 审核表单数据
      reviewForm: {
        id: null,
        projectName: null,
        status: '-1',
        comment: null
      },
      // 审核加载状态
      reviewLoading: false,
      // 审核表单验证规则
      reviewRules: {
        status: [
          { required: true, message: '请选择审核状态', trigger: 'change' }
        ],
        comment: [
          { required: true, message: '请输入审核意见', trigger: 'blur' }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        procurementProjectName: null,
        procurementCategory: null,
        procurementMethod: null,
        contractAmount: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "工程项目名称不能为空", trigger: "blur" }
        ],
      },
      // 字段选择相关
      openColumnSelect: false,
      // 所有可选的字段配置
      allColumns: [
        { prop: 'serialNumber', label: '序号' },
        { prop: 'projectName', label: '工程项目名称' },
        { prop: 'approvalAuthority', label: '立项审批单位' },
        { prop: 'approvalDocument', label: '立项批复文件' },
        { prop: 'approvalDate', label: '立项批复时间' },
        { prop: 'preliminaryDesignDocument', label: '初设批复文件' },
        { prop: 'preliminaryDesignDate', label: '初设批复时间' },
        { prop: 'approvedConstructionContent', label: '批复建设内容' },
        { prop: 'approvedBudget', label: '批复概算（万元）' },
        { prop: 'procurementProjectName', label: '采购项目名称' },
        { prop: 'procurementCategory', label: '项目类别' },
        { prop: 'procurementContent', label: '采购内容' },
        { prop: 'procurementMethod', label: '采购方式' },
        { prop: 'procurementAgent', label: '采购代理机构' },
        { prop: 'announcementTime', label: '公告时间' },
        { prop: 'announcementPlatform', label: '公告平台' },
        { prop: 'bidderContactInfo', label: '送标人及联系方式' },
        { prop: 'biddingParticipants', label: '参投单位（代理人）' },
        { prop: 'winningBidder', label: '中标单位（法人）' },
        { prop: 'reviewLocation', label: '开评审地点' },
        { prop: 'reviewTime', label: '评审时间' },
        { prop: 'ownerRepresentative', label: '业主代表' },
        { prop: 'ownerRepresentativeContact', label: '参评业主代表联系方式' },
        { prop: 'winningAnnouncementTime', label: '中标公示时间' },
        { prop: 'winningAnnouncementPlatform', label: '公示平台' },
        { prop: 'winningBidAmount', label: '中标金额' },
        { prop: 'settlementAmount', label: '结算金额' },
        { prop: 'contractName', label: '合同名称' },
        { prop: 'contractNumber', label: '合同号' },
        { prop: 'contractContent', label: '合同主要内容' },
        { prop: 'negotiationDate', label: '合同谈判日期' },
        { prop: 'contractSignDate', label: '合同签订日期' },
        { prop: 'contractAmount', label: '合同金额（万元）' },
        { prop: 'partyASignatory', label: '甲方合同签署代表' },
        { prop: 'partyBSignatory', label: '乙方合同签署代表' },
        { prop: 'projectManager', label: '项目负责人' },
        { prop: 'siteRepresentativePartyA', label: '甲方现场负责人或代表' },
        { prop: 'handlerPartyA', label: '甲方经办人及联系电话' },
        { prop: 'handlerPartyB', label: '乙方经办人及联系电话' },
        { prop: 'finalSettlementAmount', label: '最终决算金额' },
        { prop: 'isFinancialAuditCompleted', label: '是否完成财务决算审计' },
        { prop: 'isFinancialReviewCompleted', label: '是否进行财务决算评审' },
        { prop: 'createdAt', label: '创建时间' },
        { prop: 'commentData', label: '审核意见时间' },
        { prop: 'updatedAt', label: '更新时间' },
        { prop: 'comment', label: '审核意见' },
        { prop: 'status', label: '状态' }
      ],
      // 当前选中的字段
      selectedColumns: ['serialNumber', 'projectName', 'procurementProjectName', 'procurementCategory', 'procurementMethod', 'contractAmount', 'status'],
      // 默认显示的字段（初始值）
      defaultColumns: ['serialNumber', 'projectName', 'procurementProjectName', 'procurementCategory', 'procurementMethod', 'contractAmount', 'status'],
      // 导入相关
      openImport: false,
      importForm: {},
      importRules: {
        file: [
          { required: true, message: '请选择上传文件', trigger: 'blur' }
        ]
      },
    // 上传参数
    upload: {
      // 是否禁用上传
      isUploading: false,
      // 是否更新已经存在的项目数据（默认true表示默认勾选）
      updateSupport: true,
      // 设置上传的请求头部
      headers: { Authorization: 'Bearer ' + this.$store.getters.token },
      // 上传的地址
      url: process.env.VUE_APP_BASE_API + '/projectManager/project/importData'
    }
    };
  },
  created() {
    this.getList();
    // 初始化字段选择
    this.initColumnSelection();
  },
  computed: {
    // 计算可见的列
    visibleColumns() {
      return this.allColumns.filter(column => this.selectedColumns.includes(column.prop));
    }
  },
  methods: {
    /** 查询工程项目信息列表 */
    getList() {
      this.loading = true;
      listProject(this.queryParams).then(response => {
        // 状态映射
        const statusMap = {
          '-1': '未处理',
          '0': '作废',
          '1': '审核通过',
          '2': '预留'
        };

        // 金额格式化函数：转为 1,234.56 格式
        const formatMoney = (value) => {
          if (isNaN(parseFloat(value))) return '0.00';
          return parseFloat(value).toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
          });
        };

        // 需要格式化的金额字段列表
        const moneyFields = [
          'approvedBudget',     // 批准预算
          'contractAmount',     // 合同金额
          'settlementAmount',   // 结算金额
          'finalSettlementAmount', // 最终结算金额
          'winningBidAmount'    // 中标金额
        ];

        // 处理数据
        this.projectList = response.rows.map((row, index) => {
          const newRow = { ...row };

          // 添加序号，从1开始顺序编号
          newRow.serialNumber = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;

          // 格式化每个金额字段
          moneyFields.forEach(field => {
            if (row[field] !== undefined && row[field] !== null) {
              newRow[field] = formatMoney(row[field]);
            }
          });

        // 日期字段现在已经是字符串格式，不再需要格式化

          // 转换状态
          newRow.status = statusMap[row.status] || '未知状态';

          return newRow;
        });

        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 【新增】初始化 formData */
    resetFormData() {
      this.formData = {
        id: null,
        projectName: null,
        approvalAuthority: null,
        approvalDocument: null,
        approvalDate: null,
        preliminaryDesignDocument: null,
        preliminaryDesignDate: null,
        approvedConstructionContent: null,
        approvedBudget: null,
        procurementProjectName: null,
        procurementCategory: null,
        procurementContent: null,
        procurementMethod: null,
        procurementAgent: null,
        announcementTime: null,
        announcementPlatform: null,
        bidderContactInfo: null,
        biddingParticipants: null,
        winningBidder: null,
        reviewLocation: null,
        reviewTime: null,
        ownerRepresentative: null,
        ownerRepresentativeContact: null,
        winningAnnouncementTime: null,
        winningAnnouncementPlatform: null,
        winningBidAmount: null,
        settlementAmount: null,
        contractName: null,
        contractNumber: null,
        contractContent: null,
        negotiationDate: null,
        contractSignDate: null,
        contractAmount: null,
        partyASignatory: null,
        partyBSignatory: null,
        projectManager: null,
        siteRepresentativePartyA: null,
        handlerPartyA: null,
        handlerPartyB: null,
        finalSettlementAmount: null,
        isFinancialAuditCompleted: null,
        isFinancialReviewCompleted: null,
        createdAt: null,
        commentData: null,
        updatedAt: null,
        comment: null,
        status: -1
      };
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.resetFormData(); // 【修改】使用 resetFormData
      this.isEdit = false;
      this.openCreate = true; // 显示弹窗
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids[0];
      getProject(id).then(response => {
        this.formData = response.data;
        this.isEdit = true;
        this.openCreate = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProject(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProject(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除工程项目信息编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => { // 改为箭头函数
        return delProject(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功"); // 推荐统一使用 $message
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 构建导出参数，去除分页参数，确保导出所有符合条件的数据
      const exportParams = {
        projectName: this.queryParams.projectName,
        procurementProjectName: this.queryParams.procurementProjectName,
        procurementCategory: this.queryParams.procurementCategory,
        procurementMethod: this.queryParams.procurementMethod,
        contractAmount: this.queryParams.contractAmount,
        status: this.queryParams.status,
        // 传递当前选中的字段，用于按需导出（序号列由后端自动添加）
        selectedColumns: this.selectedColumns ? this.selectedColumns.join(',') : ''
        // 注意：不包含 pageNum 和 pageSize，确保导出所有数据
      };
      
      this.$confirm('是否确认导出当前查询条件下的所有工程项目信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 显示导出中的加载状态
          this.loading = true;
          return exportProject(exportParams);
        })
        .then((response) => {
          // 检查响应是否是 JSON 错误信息
          if (response.type && response.type.includes('application/json')) {
            // 将 blob 转换为 JSON 来读取错误信息
            response.text().then(text => {
              try {
                const errorData = JSON.parse(text);
                this.$message.error("导出失败：" + errorData.msg);
              } catch (e) {
                this.$message.error("导出失败：" + text);
              }
            });
            return;
          }
          
          // 处理文件流响应
          if (response && response.size > 0) {
            // 创建Blob对象
            const blob = new Blob([response], { 
              type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
            });
            
            // 创建下载链接
            const link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = '工程项目信息.xlsx';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 释放内存
            window.URL.revokeObjectURL(link.href);
            
            this.$message.success('导出成功');
          } else {
            this.$message.error('导出失败：响应数据为空');
          }
        })
        .catch((error) => {
          console.error('导出错误:', error);
          if (error.response) {
            // 服务器响应了错误状态码
            const errorMsg = error.response.data ? error.response.data : error.response.statusText;
            this.$message.error("导出失败：" + errorMsg);
          } else if (error.message && error.message.includes('cancel')) {
            // 用户取消导出
            this.$message.info("已取消导出");
          } else {
            // 其他错误
            this.$message.error("导出失败：" + (error.message || "未知错误"));
          }
        });
    },

    /** 审核按钮操作 */
    handleReview(row) {
      const id = row.id || this.ids[0];
      getProject(id).then(response => {
        const projectData = response.data;
        this.reviewForm = {
          id: projectData.id,
          projectName: projectData.projectName,
          status: projectData.status || '-1',
          comment: projectData.comment || ''
        };
        this.openReview = true;
      });
    },

    /** 关闭审核弹窗 */
    closeReview() {
      this.openReview = false;
      this.reviewLoading = false;
      this.$refs.reviewForm && this.$refs.reviewForm.clearValidate();
    },

    /** 提交审核 */
    submitReview() {
      this.$refs.reviewForm.validate(valid => {
        if (!valid) return;
        this.reviewLoading = true;
        const loading = this.$loading({ text: '正在提交审核...' });

        // 准备审核数据，包含审核时间
        const reviewData = {
          id: this.reviewForm.id,
          status: this.reviewForm.status,
          comment: this.reviewForm.comment,
          commentData: new Date()
        };

        reviewProject(reviewData)
          .then(() => {
            this.$message.success('审核成功');
            this.closeReview();
            this.getList();
          })
          .catch(() => {
            this.$message.error('审核失败');
          })
          .finally(() => {
            loading.close();
            this.reviewLoading = false;
          });
      });
    },

    /** 【新增】提交成功后刷新列表 */
    onSubmit() {
      this.getList();
      this.openCreate = false;
      this.$message.success(this.isEdit ? "修改成功" : "新增成功");
    },

    /** 字段选择相关方法 */

    // 初始化字段选择
    initColumnSelection() {
      // 从本地存储加载用户保存的字段选择，如果没有则使用默认值
      const savedColumns = localStorage.getItem('project_columns_selection');
      if (savedColumns) {
        this.selectedColumns = JSON.parse(savedColumns);
      }
    },

    // 打开字段选择弹窗
    handleColumnSelect() {
      this.openColumnSelect = true;
    },

    // 关闭字段选择弹窗
    closeColumnSelect() {
      this.openColumnSelect = false;
    },

    // 保存字段选择
    saveColumnSelection() {
      if (this.selectedColumns.length === 0) {
        this.$message.warning('请至少选择一个字段');
        return;
      }

      // 保存到本地存储
      localStorage.setItem('project_columns_selection', JSON.stringify(this.selectedColumns));

      this.closeColumnSelect();
      this.$message.success('字段选择已保存');
    },

    // 全选字段
    selectAllColumns() {
      this.selectedColumns = this.allColumns.map(column => column.prop);
    },

    // 清空字段选择
    clearColumnSelection() {
      this.selectedColumns = [];
    },

    // 导入相关方法

    /** 导入按钮操作 */
    handleImport() {
      // 先重置updateSupport为默认值true
      this.upload.updateSupport = true;
      // 再打开弹窗，确保checkbox能正确显示勾选状态
      this.openImport = true;
      // 强制Vue响应式更新
      this.$forceUpdate();
    },

    /** 下载模板操作 */
    handleDownloadTemplate() {
      // 直接下载固定的模板文件
      const link = document.createElement('a');
      link.href = '/ImportExcel.xls';
      link.download = '工程项目导入模板.xls';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },

    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.openImport = false;
      this.getList();
    },

    /** 提交上传文件 */
    submitFileForm() {
      this.$refs.upload.submit();
    },

    /** 关闭导入弹窗 */
    closeImport() {
      this.openImport = false;
      this.$refs.upload.clearFiles();
      // 不清除updateSupport，保持默认勾选状态
    },

    /** 通用下载方法 */
    download(data, fileName) {
      if (!data) {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', fileName || 'file.xlsx');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }
  }
};
</script>
